export const toJSON = (data: string, defaultValue?: any) => {
    try {
        return typeof data === "string" && data.length > 0 ? JSON.parse(data) : defaultValue || {};
    } catch (error) {
        return defaultValue || {};
    }
};

export const jsonToStr = (data: any) => {
    try {
        return JSON.stringify(data);
    } catch (error) {
        return '';
    }
};

export const isEmpty = (val: any) => {
    return val === undefined || val === null || val === '' || val.length === 0;
};

export const formatPassword = (password: string, publicKey: string, encrypt: boolean) => {
    if(!encrypt) {
        return btoa(password);
    } else {
        return null;
    }
};

/**
 * Remove empty items from an array
 * @param arr Array to filter out empty items
 * @template T Type of the items in the array
 * @param arr The array to process
 * @description This function filters out empty items from the provided array.
 * It checks each item in the array and only includes those that are not empty.
 * An item is considered empty if it is undefined, null, an empty string, or has a length of 0.
 * @returns 
 */
export const cnArray = <T>(arr?: T[]): T[] => {
    const resultArray: T[] = [];
    if(arr) {
        arr.forEach(item => {
            if(!isEmpty(item)) {
                resultArray.push(item);
            }
        });
    }
    return resultArray;
};